﻿<template>
  <el-dialog
    :title="`编辑 ${adminName} 关联组织`"
    :visible.sync="visible"
    :close-on-click-modal="false"
    width="500px"
  >
    <org-check-tree
      v-if="multiple"
      ref="orgCheckTree"
      default-visible
      v-model="orgIds"
    />
    <org-select
      v-else
      ref="orgSelect"
      v-model="orgIds"
      default-expand
    />
    <span slot="footer">
      <el-button type="primary" @click="onSubmit">确认</el-button>
      <el-button type="default" @click="onCancel">取消</el-button>
    </span>
  </el-dialog>
</template>

<script>
import OrgCheckTree from '@/pages/org/OrgCheckTree';
import OrgSelect from '@/pages/org/OrgSelect';

export default {
  components: {
    OrgCheckTree,
    OrgSelect
  },
  data() {
    return {
      visible: false,
      orgIds: [],
      adminName: '',
      multiple: true,
    }
  },
  methods: {
    open(admin) {
      this.visible = true;
      this.admin = admin;
      this.multiple = admin.roleId != 9;
      this.adminName = admin.realName;
      this.orgIds = admin.orgIds ? admin.orgIds.split(',').map(Number) : [];
      if (this.multiple) {
        if (this.$refs.orgCheckTree) {
          this.$refs.orgCheckTree.show(200);
        }
      } else {
        setTimeout(() => {
          if (this.$refs.orgSelect) {
            this.$refs.orgSelect.expand();
          }
        }, 200);
      }
    },
    async onSubmit() {
      let orgIds = this.orgIds instanceof Array ? this.orgIds : [this.orgIds];
      if (this.admin.roleId == 9 && this.orgIds == null) {
        orgIds = [];
      }
      const ret = await this.$http.post(
        '/api/admin/joinOrg',
        {adminId: this.admin.id, orgIds},
        {dataType: 'json'});
      if (ret.success) {
        this.visible = false;
        this.$message.success(ret.message);
        this.$vnode.context.$refs.table.reloadCurrentPage();
      }
    },
    onCancel() {
      this.visible = false;
      if (this.multiple) {
        this.$refs.orgCheckTree.close();
      }
    }
  },
}
</script>

<style scoped>
>>> .el-dialog__body {
  min-height: 380px;
}
</style>